package com.gopay.bis.gdb.ebank.operation;

import java.math.BigDecimal;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.gdb.ebank.gfbank.payment.merchant.PayCfg;
import com.gopay.common.constants.bank.GdbConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.gdb.ebank.GdbB2cMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.HttpTransport;
import com.gopay.remote.bank.ICertHelper;

/**
 * 广发银行B2C订单查询类
 * 
 * @GdbB2cQuery.java
 * @author zhengxue
 * @2014-11-14 下午2:23:37 www.gopay.com.cn Inc.All rights reserved.
 */
public class GdbB2cQuery {
    // 签名验签类
    private ICertHelper gdbB2cCertHelper;

    public Object query(GdbB2cMessage message) throws GopayException {
        try {
            String merchid = message.getMerID();
            String orderid = message.getBankOrderId();
            String gdbURL = PayCfg.getValue("gfbankqueryurl"); // 银行订单查询请求地址

            String signResult = gdbB2cCertHelper.sign(message);
			gdbURL = gdbURL + "?merchid=" + merchid + "&orderid=" + orderid
					+ "&returl=" + "&sign=" + signResult;
            BankLogUtils.printB2CQuerySendLog(message, gdbURL);
            // 通讯类
            HttpTransport httpTransport = new HttpTransport();
            httpTransport.setUrl(gdbURL);
            Object obj = (Object) httpTransport.submit(null);
            BankLogUtils.printB2CQueryBlackLog(message, obj);
            // 解析查询结果
            return parseQueryRes(obj, message);
        } catch (Exception e) {
            BankLogUtils.printB2CQueryExceptionLog(message, e);
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6037);
        }

    }

    /**
     * B2C订单查询结果解析
     * 
     * @param object
     * @return
     */
    public GdbB2cMessage parseQueryRes(Object object, GdbB2cMessage b2cQuery) {
        String res[];
        String result = (String) object;
        if (!result.contains("order_status")) {
            // 订单不存在
            res = result.split(",");
            b2cQuery.setRetCode(res[0]);
        } else {
            res = result.split("\\n");
            // 获取查询状态
            String orderStatus = res[0].substring(res[0].indexOf(":") + 1);
            b2cQuery.setOrderStatus(orderStatus.trim());
            if (GdbConstants.QUERY_STATUS_SUCCESS.equals(orderStatus.trim())) {
                // 查询成功
                String orderDetail[] = res[1].split("\\|\\|");
                b2cQuery.setAmount(new BigDecimal(orderDetail[1]));
                b2cQuery.setRetCode(orderDetail[3]);
            }
        }
        return b2cQuery;
    }

    public void setGdbB2cCertHelper(ICertHelper gdbB2cCertHelper) {
        this.gdbB2cCertHelper = gdbB2cCertHelper;
    }

}
